<!--子表组件-->
<template>
    <div class="submodule-wrap">
        <el-table
                ref="tableRef"
                border
                :data="isSee ? tableData :[]"
                size="small"
                empty-text="暂无数据"
        >
            <el-table-column type="selection" width="55" />
            <el-table-column v-for="(item,index) in cols" :prop="item.field_id" :label="item.label" min-width="160">
                <template #header="scope" v-if="item.required">
                    <div class="table-head-required">{{scope.column.label}}</div>

                </template>
                <template #default="scope">
                    <template v-if="!showEdit">
                        <div v-if="item.type === 'bool'">{{scope.row[item.field_id] ? '是' : '否'}}</div>
                        <template v-else>{{scope.row[item.field_id]}}</template>
                    </template>

                    <el-form ref="formRef" :model="scope.row" v-if="showEdit">
                        <el-form-item :prop="item.field_id"
                                      :rules="[{validator:validateData,required: item.required,message: item.label + '不能为空',trigger: 'blur',index: scope.$index}]"
                                      @validate="handleValidate"
                        >
                            <m-form-item :readonly="(scope.row.row_id && !isEdit) || (!scope.row.row_id && !isAppend)" :key="scope.row.row_id" :id="scope.$index" :value="scope.row[item.show_field || item.field_id]" :field="item" @m-change.self="handleChange"></m-form-item>
                        </el-form-item>
                    </el-form>
                </template>
            </el-table-column>

            <!--<el-table-column fixed="right" label="操作" width="120">
                <template #default="scope">
                    <el-button v-if="showEdit" link type="default" @click="handleClick(scope,'cancel')">确定</el-button>
                    <el-button v-if="!showEdit" link type="primary" @click="handleClick(scope,'edit')">编辑</el-button>
                    <el-button link type="danger" @click="handleClick(scope,'del')">删除</el-button>
                </template>
            </el-table-column>-->

        </el-table>
        <div class="btn-wrap" v-show="showEdit">
            <el-button link type="primary" @click="addSubData" v-if="isAppend">
                <template #icon><i class='iconfont icon-tianjia'></i></template>
                添加明细</el-button>
            <el-button link type="danger" @click="delSubData" v-if="isDelete">
                <template #icon><i class='iconfont icon-shanchu'></i></template>
                删除明细</el-button>
        </div>
    </div>
</template>

<script setup>
    import {ref,reactive,defineProps,watch} from 'vue'
    import MFormItem from '@/components/common/Form/FormItem'
    import {getAuthority} from "../../utils/permission";

    /**
     * 属性
     * dtlData {Array} 明细数据
     * cols {Array} 显示表格列参数
     * showEdit {Boolean} 显示编辑可修改状态（false：表格行不可编辑、按钮隐藏）
     * id {String} 明细表id
     * authId {String} 明细表权限id
     * */
    const props = defineProps(['dtlData','cols','showEdit','id','authId'])



    let tableRef = ref(null),
      tableData = reactive([]),
      /*cols = ref([
        {field_id: 'shuttle_name',label: '班车名称',type: 'text',required: true },
        {field_id: 'packag_type_id',show_field: 'packag_type_name',label: '班车方向名称',type: 'reference' },
        {field_id: 'Order_amount',label: '序号',type: 'number' },
        {field_id: 'sale_minimum',label: '可售最少数',type: 'number' },
        {field_id: 'departure_time',label: '发车时间',type: 'datetime' },
        {field_id: 'arrive_time',label: '到达时间',type: 'datetime' },
        {field_id: 'mark',label: '说明',type: 'textarea' },
        {field_id: 'is_used',label: '使用标识',type: 'bool' },]),*/
      // showEdit = ref(false),
      iptForm = reactive([]),
      formRef = ref(null),
      isSee = ref(true),    //可见权限
      isAppend = ref(true),    //新增权限
      isEdit = ref(true),    //编辑权限
      isDelete = ref(true)   //删除权限

    watch(() => props.dtlData,(val)=>{
      console.log('明细数据',val);
      tableData = val;
    },{immediate: true});

    watch(() => props.authId, (val) => {
      let auth = getAuthority(val);
      if (auth){
        let {is_see,is_append,is_edit,is_delete} = auth;
        isSee.value = is_see
        isAppend.value = is_append
        isEdit.value = is_edit
        isDelete.value = is_delete
      }
    },{immediate: true})

    //表格表单变化
    function handleChange(val,index) {
      //编辑数据传入行id
      if (iptForm[index] === undefined && tableData[index]){
        iptForm[index] = {row_id: tableData[index].row_id}
      }

      iptForm[index] = {...iptForm[index],...val};
      tableData[index] = {...tableData[index],...val};
      console.log(tableData);
      console.log('表格数据：',iptForm);
      console.log(formRef);
    }
    //自定义验证控制器
    function validateData(rule,value,callback) {
      if (!rule.required) {
        callback();
        return
      }
      //rule中传入表格数据索引index
      //blur后判断值为undefined以及原表格数据为空是提示错误，原表格数据不为空时未修改字段不提示错误
      if (value === undefined) {
        if (!tableData[rule.index][rule.fullField]) callback(new Error())
        else callback()
      }else if (!value) {
        callback(new Error())
      }
      else callback()
    }
    //验证表格
    async function validateAll() {
      let validates = [],valid = true
      formRef.value && formRef.value.forEach((item,index) =>{
        validates.push(validateItem(index))
      });
      await Promise.all(validates).then(res =>{
        valid = res.every(item => item === true)
      });
      console.log(valid);
      return valid;
    }
    function validateItem(key) {
      return new Promise((resolve,reject) => {
        formRef.value[key].validate(isValid => {
          resolve(isValid)
        })

      })
    }
    //添加明细数据
    function addSubData(){
      tableData.push({});
      iptForm[tableData.length-1] = {};

    }
    //删除明细数据
    function delSubData() {
      let rows = tableRef.value.getSelectionRows(); //已选行
      if (!rows.length){
        ElMessage({type: 'warning',message: '请先选择数据行'});
        return
      }

      for (let i = tableData.length;i>=0;i--){
        let item = tableData[i]
        if (rows.indexOf(item) >= 0) {
          tableData.splice(i,1)
          iptForm.splice(i,1)
        }
      }
    }

    defineExpose({validateAll,data:iptForm,id: props.id})
</script>

<style scoped lang="less">
    .submodule-wrap{
        padding-bottom: 10px;
        .table-head-required{
            position: relative;
            &:before{
                content: '* ';
                color: #ff7679;
            }
        }
        .btn-wrap{
            padding-top: 10px;
        }
    }
</style>
